<?php
/**
 * alltosun.com 百度授权登录 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
*/
class Action
{
    private $appid;
    private $appkey;
    private $callback; // 回调地址
    private $password;
    private $hash;

    function __construct()
    {
        $openapi = Config::get('openapi');
        $this->appid = $openapi['baidu'][0];
        $this->appkey = $openapi['baidu'][1];
        $this->callback = $openapi['baidu'][2];
        $this->hash = user_helper::random_hash(6);
        //echo $this->appid;
    }
    function __call($action = '', $param = array())
    {

    }

    /**
     * 百度授权页面加载
     */
    public function login()
    {
        $isBind = Request::Get('bind', '0');

        if(user_helper::get_user_id() && !$isBind) {
            return array('您已经登录过了。', 'error', AnUrl('user/setting'));
        }
        if(is_mobile()) {
            $display_mobile = '&display=mobile';
        } else {
            $display_mobile = '';
        }
        $login_url = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id="
                .$this->appid. "&redirect_uri=" . urlencode($this->callback).$display_mobile;
        $rfUrl = Request::Get('rfUrl', '');
        if($isBind) {
            $_SESSION['bind'] = $isBind;
            if(!user_helper::get_user_id()) {
                return array('您需要先登录才可以绑定第三方帐号。', 'error', AnUrl('user/login'));
            }
        } else {
            $_SESSION['bind'] = 0;
        }

        if(!isset($_SESSION['login_callback'])) {
            $_SESSION['login_callback'] = user_helper::get_jump_url($rfUrl);
        }
        //echo $login_url;
        Response::redirect($login_url);
    }

    /**
     * 百度授权回调方法
     */
    public function callback()
    {
        $code = Request::getParam('code', '');
        if (isset($code) && !empty($code)) {
            $token_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="
                    .$code. "&client_id=" . $this->appid. "&client_secret=". $this->appkey ."&redirect_uri=" . urlencode($this->callback);

            $response = curl_request($token_url, 'get');
            $msg = json_decode($response, true);
            if(isset($msg['error']) && !empty($msg['error'])) {
                return("错误：".$msg['error_description']);
            }
            //使用Access Token来获取用户的OpenID
            $graph_url = "https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token=".$msg['access_token'];
            $str  = curl_request($graph_url, 'get');
            $user = json_decode($str, true);
//             var_dump($user);
//             return;
            if (!isset($user['userid'])) // 用户userid未获取成功
            {
                return("错误：获取用户信息失败！");
            } else {
                $connect_info = _uri('connect_baidu', array('connect_user_id'=>$user['userid']));
                $user['avatar'] = "http://tb.himg.baidu.com/sys/portrait/item/".$user['portrait'];
                $user['user_name'] = $user['username'];
                if (!$connect_info) {   //如果没有授权过，进行记录授权
                    $info = array(
                        'connect_user_id'    =>    $user['userid'],
                        'connect_site_id'    =>    7,
                        'connect_user_name'  =>    $user['username'],
                        'access_token'       =>    $msg['access_token'],
                        'expires_in'         =>    $msg['expires_in']+time(),
                        'scope'              =>    $msg['scope'],
                        'session_key'        =>    $msg['session_key'],
                        'session_secret'     =>    $msg['session_secret']
                    );

                    if($_SESSION['bind']) {
                        if(!user_helper::get_user_id()) {
                            return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                        }
                        $info['user_id'] = user_helper::get_user_id();
                        $connect_id = _model('connect_baidu')->create($info);
                        if($connect_id) {
                            unset($_SESSION['bind']);
                            return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                        }
                    }

                    $connect_id = _model('connect_baidu')->create($info);
                    $_SESSION['associatedConnectInfo']['id'] = $connect_id;
                    $_SESSION['associatedConnectInfo']['type'] = 'baidu';
                    $_SESSION['associatedConnectInfo']['user_info'] = $user;
                    Response::redirect(AnUrl('openapi/choose_bind'));
                } else {
                    $info = array(
                        'connect_user_name'  =>    $user['username'],
                        'access_token'       =>    $msg['access_token'],
                        'expires_in'         =>    $msg['expires_in']+time(),
                        'scope'              =>    $msg['scope'],
                        'session_key'        =>    $msg['session_key'],
                        'session_secret'     =>    $msg['session_secret']
                    );
                    _model('connect_baidu')->update($connect_info['id'], $info);
                    if(!$connect_info['user_id']) {
                        if($_SESSION['bind']) {
                            if(!user_helper::get_user_id()) {
                                return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                            }
                            $affected = _model('connect_baidu')->update($connect_info['id'], array('user_id' => user_helper::get_user_id()));
                            if($affected) {
                                unset($_SESSION['bind']);
                                return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                            }
                        }
                        $_SESSION['associatedConnectInfo']['id'] = $connect_info['id'];
                        $_SESSION['associatedConnectInfo']['type'] = 'baidu';
                        $_SESSION['associatedConnectInfo']['user_info'] = $user;
                        Response::redirect(AnUrl('openapi/choose_bind'));
                    } else {
                        if($_SESSION['bind']) {
                            unset($_SESSION['bind']);
                            return array('此百度帐号已经被其他帐号绑定过了', 'error', AnUrl('user/setting/account_bind'));
                        }
                        $user_info = _uri('user', $connect_info['user_id']);
                        //绑定过更新下用户信息、同步登录
                        $info = array(
                                'nickname'         =>    $user['username'],
                                'user_from'        =>    'baidu',
                                'last_login_time'  =>    date('Y-m-d H:i:s', time())
                        );
                        if(empty($user_info['nickname'])) {
                            $info['nickname'] = $user['username'];
                        }
                        if(empty($user_info['avatar'])) {
                            $info['avatar'] = "http://tb.himg.baidu.com/sys/portrait/item/".$user['portrait'];
                        }
                        _model('user')->update(array('id'=>$connect_info['user_id']), $info);

                        $this->connect_update($connect_info['id'], $user, $msg);

                        $return_info = $this->user_login($connect_info['user_id']);
                        if($return_info['info'] != 'error') {
                            echo $return_info;
                        } else {
                            return($return_info['msg']);
                        }
                    }
                }
             }
        } else {
            return("验证信息过期");
        }
    }

    private function user_login($user_id)
    {
        // 本站登录，写入session
        $user_info = _uri('user', $user_id);
        user_helper::session_update($user_info, 'baidu');
        //同步登录ucenter
        $callback = $_SESSION['login_callback'];
        
        $return_info = user_helper::uc_login($user_info['uc_id'], '', $callback,0,1);
        return $return_info;
    }


}